package com.qdu.pokerun.util;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.I18NBundle;
import com.badlogic.gdx.utils.PropertiesUtils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;

public class DatabaseUtil {

    public static final String DRIVER_CLASS;
    private static final String URL;
    private static final String USERNAME;
    private static final String PASSWORD;

    private static I18NBundle rb = I18NBundle.createBundle(Gdx.files.internal("config/dbconfig"));

    /**
     * 静态代码块，用于从属性文件读取数据库连接用用户名、密码、驱动类和数据库url
     */
    static {
        URL = rb.get("jdbc.url");
        USERNAME = rb.get("jdbc.username");
        PASSWORD = rb.get("jdbc.password");
        DRIVER_CLASS = rb.get("jdbc.driver");
    }

    /**
     * 用于取得数据库连接。读取外部配置文件作为连接参数
     *
     * @return 一个sql连接对象
     */
    public static Connection getConnection() {

        Connection con = null;

        try {
            Class.forName(DRIVER_CLASS);
            con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return con;
    }

    /**
     * 用于关闭一个数据库的连接，保证数据库安全与程序正常运行
     *
     * @param rs   要关闭的结果集
     * @param stmt 要关闭的语句集
     * @param con  要关闭的连接
     */
    public static void close(ResultSet rs, Statement stmt, Connection con) {
        try {
            if (rs != null)
                rs.close();
            if (stmt != null)
                stmt.close();
            if (con != null)
                con.close();
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
}
